package top.v5it.japi.plus.extra.web;

import org.springframework.web.bind.annotation.*;
import top.v5it.japi.plus.core.spring.web.JapiEada;
import top.v5it.japi.plus.extra.exception.JapiQueryException;
import top.v5it.japi.plus.extra.service.JapiQueryService;
import top.v5it.japi.plus.log.JapiOperLog;
import top.v5it.japi.plus.support.limit.JapiLimit;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 统一分页查询控制器，可支持 POST 或者 GET 方法
 *
 * <pre>
 * ### 示例一
 * GET http://localhost:7474/query/account?page=1&size=10&sort=desc&properties=createTime&name=jack
 * Content-Type: application/x-www-form-urlencoded
 * Accept: application/json
 *
 * ### 示例二
 * GET http://localhost:7474/query/account
 * Content-Type: application/x-www-form-urlencoded
 * Accept: application/json
 *
 * page=1&size=10&sort=desc&properties=createTime&name=jack
 *
 * ### 示例三
 * GET http://localhost:7474/query/account?page=1&size=10&sort=desc&properties=createTime
 * Content-Type: application/x-www-form-urlencoded
 * Accept: application/json
 *
 * name=jack&tel=18698542574
 *
 * ### 示例四
 * GET http://localhost:7474/query/account
 * Content-Type: application/json
 * Accept: application/json
 *
 * {
 *   "page": 1,
 *   "size": 10,
 *   "sort": "desc",
 *   "properties": "createTime",
 *   "name": "jack"
 * }
 *
 * ### 示例五
 * GET http://localhost:7474/query/account?page=1&size=10&sort=desc&properties=createTime
 * Content-Type: application/json
 * Accept: application/json
 *
 * {
 *   "name": "jack"
 * }
 * </pre>
 *
 * @author zhanpu
 * @date 2022/8/10
 */
@RestController
public class JapiQueryController extends JapiBaseController {

    private static final String QUERY_URL = "query/{bean}";

    @JapiEada
    @JapiOperLog("分页查询")
    @JapiLimit(limitKey = QUERY_URL)
    @RequestMapping(value = QUERY_URL, method = {RequestMethod.GET, RequestMethod.POST})
    public Object query(@PathVariable("bean") String bean,
                        @RequestBody(required = false) Map<String, Object> json, HttpServletRequest request) {
        JapiQueryService service;
        try {
            service = getBean(bean);
        } catch (RuntimeException e) {
            throw new JapiQueryException(e);
        }
        json = toMap(json, request);
        return service.query(json, bean);
    }

}
